package ${package.Advice};

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.layuiframework.stereotype.advice.MyMetaObjectHandler;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


@Configuration
@MapperScan(basePackages = "${package.Mapper}")
public class DataSourceConfig{

    @Primary
    @Bean(name = "webgisDatasource")
    @Qualifier("webgisDatasource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource webgisDatasource() {
        return new DruidDataSource();
    }

    @Primary
    @Bean(name = "mybatisProperties")
    @Qualifier("mybatisProperties")
    @ConfigurationProperties(prefix = "mybatis-plus")
    public MybatisPlusProperties properties() {
        return new MybatisPlusProperties();
    }

    @Primary
    @ConditionalOnBean(MybatisPlusProperties.class)
    @Bean
    public MybatisSqlSessionFactoryBean webgisSessionFactory(@Qualifier("webgisDatasource") DataSource dataSource,@Qualifier("mybatisProperties") MybatisPlusProperties properties) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setGlobalConfig(properties.getGlobalConfig().setMetaObjectHandler(new MyMetaObjectHandler()));
        factoryBean.setConfiguration(properties.getConfiguration());
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(properties.getMapperLocations()[0]));
        factoryBean.setConfigurationProperties(properties.getConfigurationProperties());
        return factoryBean;
    }

    @Primary
    @Bean
    public DataSourceTransactionManager webgisTransactionManager(@Qualifier("webgisDatasource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}